import jssc.SerialPort;
import jssc.SerialPortEvent;
import jssc.SerialPortEventListener;
import jssc.SerialPortException;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;

@Slf4j
public class SerialCallerIDReceiver {

    public static void main(String[] args) {
        SerialCallerIDReceiver scir=new SerialCallerIDReceiver();
        scir.init();
    }

    public  void init(){
        String settings="COM4:9600:8:1:0:AT+VCID=1";
        String[] settingsArr = settings.split("\\|\\|");
        for (String setting : settingsArr) {
            connectDevice(setting);
        }
    }
    private  void connectDevice(String setting){
        String[] settingsList = setting.split(":");
        String portName = settingsList[0];
        int baudRate = Integer.parseInt(settingsList[1]);
        int databits = Integer.parseInt(settingsList[2]);
        int stopbits = Integer.parseInt(settingsList[3]);
        int parity = Integer.parseInt(settingsList[4]);
        String enableCallerIdCmd = settingsList[5] + "\r\n";
        SerialPort serialPort = new SerialPort(portName);
        try {
            serialPort.openPort();
            serialPort.setParams(baudRate, databits, stopbits, parity);
            serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN | SerialPort.FLOWCONTROL_RTSCTS_OUT);
            serialPort.addEventListener(new PortReader(serialPort), SerialPort.MASK_RXCHAR | SerialPort.MASK_ERR);
            serialPort.writeString(enableCallerIdCmd);
            log.info("Serial Caller ID Service is initiated successfully!");
        } catch (SerialPortException ex) {
            log.error("There is an error on creating Serial Caller ID Service: ", ex);
        }
    }




    class PortReader implements SerialPortEventListener{
        SerialPort serialPort;
        public PortReader(SerialPort serialPort) {
            this.serialPort = serialPort;
        }
        @Override
        public void serialEvent(SerialPortEvent event) {
            if (event.isRXCHAR()) {
                if (event.getEventValue() > 0) {
                    try {
                        final byte buffer[] = serialPort.readBytes(event.getEventValue());
                        final String data = new String(buffer);
                        if (log.isDebugEnabled()) {
                            log.debug("Received data: {}", data);
                        }
                        if (data.indexOf("NMBR") >= 0) {
                            log.info("Incoming call: {}, buffer:{}", data, Arrays.toString(buffer));
                            System.out.println("Incoming call"+data);
                        }
                    } catch (SerialPortException ex) {
                        log.error("Error in receiving data from device: ", ex);
                    }
                }
            } else {
                log.info("Unhandled Event: type={}, value={}", event.getEventType(), event.getEventValue());
            }

        }
    }

}
